package xreflect

import (
	"encoding/json"
	"reflect"
	"strconv"

	"gitee.com/xuyiping_admin/pkg/xerr"
)

var ErrUnkownType = xerr.New("unknown type")

func SetString(target reflect.Value, val string) error {
	if target.Kind() == reflect.String {
		target.SetString(val)
		return nil
	}
	return json.Unmarshal([]byte(val), target.Addr().Interface())
}

func ToString(target reflect.Value) (string, error) {
	switch target.Kind() {
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return strconv.FormatInt(target.Int(), 10), nil
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return strconv.FormatUint(target.Uint(), 10), nil
	case reflect.Float32:
		return strconv.FormatFloat(target.Float(), 'f', -1, 32), nil
	case reflect.Float64:
		return strconv.FormatFloat(target.Float(), 'f', -1, 64), nil
	case reflect.Bool:
		return strconv.FormatBool(target.Bool()), nil
	case reflect.String:
		return target.String(), nil
	default:
		return "", ErrUnkownType
	}
}
